package com.clusterswisdom.horn.api.ioc.api;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;

import com.clusterswisdom.horn.api.ioc.ResponseProcessor;

public class ResponseConfig implements Serializable {

	private static final long serialVersionUID = -7205143553520829235L;

	private ResponseType type; //status, data, push
	
	private String url;
	
	private String struct;
	
	private String property;
	
	private boolean saveData;
	
	private String[] fields;
	
	private ResponseProcessor processor;
	
	private ResponseFormater formater;
	
	private List<ResponseField> responseFields;
	
	public ResponseConfig(Element element) {
		this.type = ResponseType.findByName(element.attributeValue("type"));
		this.url = element.attributeValue("url");
		this.struct = element.attributeValue("struct");
		this.property = element.attributeValue("property");
		this.saveData = !"false".equalsIgnoreCase("saveData");
		
		String processorClass = element.attributeValue("processor");
		if (processorClass != null) {
			this.type = ResponseType.DEFINE;
			try {
				processor = (ResponseProcessor)Thread.currentThread().getContextClassLoader().loadClass(processorClass).newInstance();
			
			}catch (Exception e) {
				e.printStackTrace();
				
			}
		}
		
		String fieldsValue = element.attributeValue("fields");
		if (fieldsValue != null) {
			fields = fieldsValue.split("[,]");
		}
		
		this.responseFields = getResponseFields(element);
	}

	public ResponseType getType() {
		return type;
	}

	public String getUrl() {
		return url;
	}

	public String getStruct() {
		return struct;
	}

	public String getProperty() {
		return property;
	}

	public boolean isSaveData() {
		return saveData;
	}

	public String[] getFields() {
		return fields;
	}

	public ResponseProcessor getProcessor() {
		return processor;
	}

	public ResponseFormater getFormater() {
		return formater;
	}
	
	public List<ResponseField> getResponseFields() {
		return responseFields;
	}

	@SuppressWarnings("unchecked")
	private List<ResponseField> getResponseFields(Element element) {
		if (element == null) {
			return new ArrayList<ResponseField>(0);
		}
		
		List<ResponseField> fields = new ArrayList<ResponseField>(4);
		Iterator<Element> fieldIterator = element.elementIterator("field");
		while (fieldIterator.hasNext()) {
			fields.add(new ResponseField(fieldIterator.next()));
		}
		
		return fields;
	}
}